﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Linq.Expressions;
using XYAC.Framework.MonitorTireMaterialManual.Context;
using XYAC.Framework.MonitorTireMaterialManual.DataExporter;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Context;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Models;
using XYAC.Framework.MonitorTireMaterialManual.OracleRemoteDB;

namespace XYAC.Framework.MonitorTireMaterialManual.Services
{
    public class LocalDataService : ServiceBase<int, LocalDataContext>, ILocalDataService
    {
        private readonly ILogger _logger;

        public LocalDataService(IOptionsMonitor<AppConfig> appConfig, ILogger<LocalDataService> logger, IServiceProvider provider) : base(appConfig, logger, provider)
        {
            _logger = logger;
        }

        public bool CreateDb()
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var flag = Db.Database.EnsureCreated();
                if (flag)
                {
                    var eqp1 = new EquipmentMapping
                    {
                        EqpNo = "REX002",
                        EqpName = "1#胎面",
                        EqpType = "1"
                    };
                    var eqp2 = new EquipmentMapping
                    {
                        EqpNo = "REX004",
                        EqpName = "2#胎面",
                        EqpType = "1"
                    };
                    var eqp3 = new EquipmentMapping
                    {
                        EqpNo = "DEX001",
                        EqpName = "6#胎面",
                        EqpType = "1"
                    };
                    var eqp4 = new EquipmentMapping
                    {
                        EqpNo = "DEX003",
                        EqpName = "7#胎面",
                        EqpType = "1"
                    };
                    var eqp5 = new EquipmentMapping
                    {
                        EqpNo = "REX001",
                        EqpName = "1#胎侧",
                        EqpType = "2"
                    };
                    var eqp6 = new EquipmentMapping
                    {
                        EqpNo = "REX003",
                        EqpName = "2#胎侧",
                        EqpType = "2"
                    };
                    var eqp7 = new EquipmentMapping
                    {
                        EqpNo = "DEX002",
                        EqpName = "4#胎侧",
                        EqpType = "2"
                    };
                    Db.AddRange(new List<EquipmentMapping>()
                    {
                        eqp1, eqp2, eqp3, eqp4, eqp5, eqp6,eqp7
                    });
                    Db.SaveChanges();
                }
                return flag;
            }
        }


        internal int DeleteSpecInfoSyncMappingEntity(IEnumerable<string> preRemoveSpecKey)
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specs = Db.SpecInfoSyncMapping.Where(T => preRemoveSpecKey.Contains(T.SpecName));
                Db.SpecInfoSyncMapping.RemoveRange(specs);

                return Db.SaveChanges();
            }
        }

        internal IEnumerable<SpecInfoSyncMapping> GetSpecInfoSyncMappingEntity(string[] findedSpecNames)
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specs = Db.SpecInfoSyncMapping.Where(T => findedSpecNames.Contains(T.SpecName));

                return specs;
            }
        }

        internal SpecInfoSyncMapping GetSpecInfoSyncMappingByName(string typeName)
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specs = Db.SpecInfoSyncMapping.FirstOrDefault(T => typeName == T.SpecName);

                return specs;
            }
        }

        internal int Update(SpecInfoSyncMapping findedMapping)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                Db.Update(findedMapping);
                return Db.SaveChanges();
            }
        }

        internal int Add(SpecInfoSyncMapping mappingEntity)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                Db.Add(mappingEntity);
                return Db.SaveChanges();
            }
        }

        internal int DeleteSpecInfoSyncMapping(IEnumerable<string> preRemoveSpecKey)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specinfos = Db.SpecInfoSyncMapping.Where(T => preRemoveSpecKey.Contains(T.SpecName));
                Db.RemoveRange(specinfos);
                return Db.SaveChanges();
            }
        }

        internal IEnumerable<SpecInfoSyncMapping> GetSpecInfoSyncMapping(string[] findedSpecNames)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specinfos = Db.SpecInfoSyncMapping.Where(T => findedSpecNames.Contains(T.SpecName));
                return specinfos;
            }
        }


        /// <summary>
        /// 定期删除LocalRecord记录数据
        /// </summary>
        /// <param name="days"></param>
        /// <returns></returns>
        public int RemoveTimeovered(int days)
        {
            int ret = 0;
            using (var scope = Provider.CreateScope())
            {
                try
                {

                    var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                    // 计算30天前的日期
                    var thresholdDate = DateTime.Now.AddDays(-30);

                    // 查询出 YB_LOT_INSPECT 在30天前的记录 
                    var oldInspect = Db.YB_LOT_INSPECT
                                            .Where(record => record.PLAN_DATE.HasValue && record.PLAN_DATE.Value < thresholdDate)
                                            .ToList();


                    if (oldInspect.Any())
                    {
                        // 删除这些记录
                        Db.YB_LOT_INSPECT.RemoveRange(oldInspect);
                    }
                    // 保存更改
                    ret = Db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Logger?.LogError($"定期清理YB_LOT_INSPECT失败:{ex.Message}", ex);
                }
            }
            return ret;
        }



        internal int GetCount<T>() where T : class, new()
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                return Db.Set<T>().Count();
            }
        }
        internal async Task<List<T>> GetPageAsync<T>(
     int pageIndex,
     int pageSize,
     List<Expression<Func<T, bool>>> filterConditions = null,
     List<(Expression<Func<T, object>> KeySelector, bool Descending)> orderConditions = null)
     where T : class, new()
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                IQueryable<T> data = Db.Set<T>();

                // 应用过滤条件
                if (filterConditions != null)
                {
                    foreach (var condition in filterConditions)
                    {
                        data = data.Where(condition);
                    }
                }

                // 应用排序条件
                bool isOrdered = false;

                if (orderConditions != null && orderConditions.Any())
                {
                    foreach (var (KeySelector, Descending) in orderConditions)
                    {
                        if (!isOrdered)
                        {
                            data = Descending ? data.OrderByDescending(KeySelector) : data.OrderBy(KeySelector);
                            isOrdered = true;
                        }
                        else
                        {
                            var orderedData = (IOrderedQueryable<T>)data;
                            data = Descending ? orderedData.ThenByDescending(KeySelector) : orderedData.ThenBy(KeySelector);
                        }
                    }
                }

                // 确保 pageIndex 为非负数，且 pageSize 为正数
                if (pageIndex < 0)
                    pageIndex = 0;
                    //throw new ArgumentOutOfRangeException(nameof(pageIndex), "pageIndex 必须为非负数。");
                if (pageSize <= 0)
                    pageSize = 10;
                    //throw new ArgumentOutOfRangeException(nameof(pageSize), "pageSize 必须为正数。");

                return await data.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync();
            }
        }


        internal SpecInfoSyncMapping GetFirstSpecInfoSyncMapping(Func<SpecInfoSyncMapping, bool> condition)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                return Db.SpecInfoSyncMapping.FirstOrDefault(condition);
            }
        }



        #region 上传今日数据

        public int SyncSemiSteelSideInspectionReportToRemote<TContext>(int RowData = 20) where TContext : ReportContext
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    using (var Db = scope.ServiceProvider.GetService<CurrentReportContext>())
                    {
                        //远程数据库上下文
                        using (var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>())
                        {

                            var localReport = Db.SemiSteelSideInspectionReport.Where(T => T.SyncState != true).OrderBy(T => T.ID).Take(20).ToList();
                            if (localReport.Count == 0)
                            {
                                return 0;
                            }
                            using (var localTrans = Db.Database.BeginTransaction())
                            {
                                try
                                {
                                    using (var remoteTrans = remoteDb.Database.BeginTransaction())
                                    {
                                        try
                                        {

                                            foreach (var row in localReport)
                                            {
                                                row.SyncState = true;
                                            }

                                            var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();
                                            remoteDb.AddRange(processSteps);
                                            var tempRemote = remoteDb.SaveChanges();

                                            Db.UpdateRange(localReport);
                                            var tempLocal = Db.SaveChanges();

                                            if (tempLocal == tempRemote)
                                            {
                                                localTrans.Commit();
                                                remoteTrans.Commit();
                                                ret = tempRemote;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            localTrans.Rollback();
                                            remoteTrans.Rollback();
                                            Logger?.LogError(ex.Message, ex);
                                            throw;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {

                                    localTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                    throw;
                                }
                            }
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncSemiSteelTreadScanReportToRemote<TContext>(int RowData = 20) where TContext : ReportContext
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    using (var Db = scope.ServiceProvider.GetService<CurrentReportContext>())
                    {
                        //远程数据库上下文
                        using (var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>())
                        {
                            var localReport = Db.SemiSteelTreadScanReport.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(RowData).ToList();
                            //var count1 = Db.SemiSteelTreadScanReport.Where(T => T.SyncState == false).Count();
                            //var count2 = Db.SemiSteelTreadScanReport.Where(T => T.SyncState != false).Count();
                            //var count3 = Db.SemiSteelTreadScanReport.Count();
                            //Debug.WriteLine($"totalCount:{count3} count1:{count1} count2:{count2}");
                            if (localReport.Count == 0)
                            {
                                return 0;
                            }
                            using (var localTrans = Db.Database.BeginTransaction())
                            {
                                try
                                {
                                    using (var remoteTrans = remoteDb.Database.BeginTransaction())
                                    {
                                        try
                                        {
                                            var processSteps = localReport.AsParallel().Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();

                                            remoteDb.AddRange(processSteps);
                                            var tempRemote = remoteDb.SaveChanges();


                                            foreach (var row in localReport)
                                            {
                                                row.SyncState = true;
                                            }

                                            Db.UpdateRange(localReport);
                                            var tempLocal = Db.SaveChanges();

                                            if (tempLocal == tempRemote)
                                            {
                                                localTrans.Commit();
                                                remoteTrans.Commit();
                                                ret = tempRemote;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            localTrans.Rollback();
                                            remoteTrans.Rollback();
                                            Logger?.LogError(ex.Message, ex);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {

                                    localTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }
        
        public int SyncSemiSteelTriangleRubberReportToRemote<TContext>(int RowData = 20) where TContext : ReportContext
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = scope.ServiceProvider.GetService<CurrentReportContext>();
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelTriangleRubberReport.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();
                                    //foreach (var processStep in processSteps)
                                    //{
                                    //    remoteDb.Add(processStep);
                                    //}
                                    remoteDb.AddRange(processSteps);

                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {

                            localTrans.Rollback();
                            Logger?.LogError(ex.Message, ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }


        public int SyncPreCheckReportToRemote<TContext>(int RowData = 20) where TContext : ReportContext
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = scope.ServiceProvider.GetService<CurrentReportContext>();
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.PreCheckReport.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {
                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                        row.LastSyncDate= DateTime.Now;
                                        row.IsDeleted = false;
                                    }
                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();

                                    //remoteDb.Add(new YB_PROCESS_STEP
                                    //{
                                    //    LJ_ID = 10,
                                    //    EQP = "123",
                                    //    EQP_TYPE = "3",
                                    //    CREATION_DATE = DateTime.Now,
                                    //    RECEIVE_FLAG = "PENDING",
                                    //    PART_NUMBER = "1232",
                                    //     PLAN_ID = "23432",
                                    //      RECIPE_ID=0,
                                    //       RECORD_DATE = DateTime.Now,
                                    //        IsDeleted = false,
                                    //         ID = 0,
                                    //});
                                    //这里的保存，需要给字段LJ_ID值方可存储成功。
                                    remoteDb.AddRange(processSteps);
                                    //processSteps[3].LJ_ID = 193;
                                    //remoteDb.Add(processSteps[3]);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                    this._logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {

                            localTrans.Rollback();
                            this._logger?.LogError(ex.Message, ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this._logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        #endregion

        #region 上传昨日数据
        public int SyncSemiSteelSideInspectionReport_YST_ToRemote(int RowData = 20)
        {
           return SyncSemiSteelSideInspectionReport_SpecDt_ToRemote(DateTime.Now.Date.AddDays(-1));
        }

        public int SyncSemiSteelTreadScanReport_YST_ToRemote(int RowData = 20)
        {
            return SyncSemiSteelTreadScanReport_SpecDt_ToRemote(DateTime.Now.Date.AddDays(-1));
        }

        public int SyncSemiSteelTriangleRubberReport_YST_ToRemote(int RowData = 20)
        {
            return SyncSemiSteelTriangleRubberReport_SpecDt_ToRemote(DateTime.Now.Date.AddDays(-1));
        }
        public int SyncPrecheckTreadScanReport_YST_ToRemote(int RowData = 20)
        {
            return SyncPrecheckTreadScanReport_SpecDt_ToRemote(DateTime.Now.Date.AddDays(-1));
        }

        public int SyncSemiSteelTriangleRubberReport_SpecDt_ToRemote(DateTime dt, int RowData = 20)
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(dt));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelTriangleRubberReport.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            localTrans.Rollback();
                            Logger?.LogError(ex.Message, ex);
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncSemiSteelSideInspectionReport_SpecDt_ToRemote(DateTime dt, int RowData = 20)
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(dt));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelSideInspectionReport.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            localTrans.Rollback();
                            Logger?.LogError(ex.Message, ex);
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncSemiSteelTreadScanReport_SpecDt_ToRemote(DateTime dt, int RowData = 20)
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(dt));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelTreadScanReport.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {
                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            localTrans.Rollback();
                            Logger?.LogError(ex.Message, ex);
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncPrecheckTreadScanReport_SpecDt_ToRemote(DateTime dt, int RowData = 20)
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(dt));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.PreCheckReport.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {
                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP(JsonSerializeHelper.DeserializeObjectFromJson<DataFile>(T.DataFileJson))).ToList();
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            localTrans.Rollback();
                            Logger?.LogError(ex.Message, ex);
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }
        #endregion
    }
}
